<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix header-box">
        <div>
          <el-button @click="back" icon="el-icon-arrow-left">返回</el-button>
          <span style="margin-left: 10px">{{
            $route.query.id ? ($route.query.type == 1 ? '编辑教师' : '教师详情') : '新增教师'
          }}</span>
        </div>
      </div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <div class="title">
          <span>基本信息</span>
        </div>
        <el-form-item label="姓名" prop="username">
          <el-input :disabled="$route.query.type == 2" v-model="ruleForm.username" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="idcard">
          <el-input
            :disabled="$route.query.type == 2"
            maxlength="18"
            v-model="ruleForm.idcard"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            :disabled="$route.query.type == 2"
            v-model="ruleForm.mobile"
            maxlength="11"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证照片">
          <el-form-item prop="idcard_img" style="float: left">
            <div class="photo_item">
              <el-upload
                v-if="$route.query.type != 2"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                accept=".jpg, .png, .jpeg"
                :before-upload="beforeAvatarUpload"
                :http-request="(file) => handleAvatarSuccess(file, 'idcard_img')"
              >
                <img v-if="ruleForm.idcard_img" :src="ruleForm.idcard_img" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="avatar-uploader" v-if="$route.query.type == 2">
                <el-image
                  v-if="ruleForm.idcard_img"
                  :src="ruleForm.idcard_img"
                  :preview-src-list="[ruleForm.idcard_img]"
                  class="avatar"
                ></el-image>
              </div>
              <div class="photo_p">
                <p class="photo_p_t">身份证人像面</p>
                <p class="photo_p_t2">图片大小不超过5M</p>
                <p class="photo_p_t2">图片分辨率不低于72dpi</p>
                <el-popover placement="top-start" width="400" trigger="hover">
                  <img style="width: 100%" src="../../assets/images/id-card-2.png" alt="" />
                  <el-button slot="reference" style="padding: 0 !important" type="text">查看示例</el-button>
                </el-popover>
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="idcard_img2" style="float: left">
            <div class="photo_item">
              <el-upload
              v-if="$route.query.type != 2"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                accept=".jpg, .png, .jpeg"
                :before-upload="beforeAvatarUpload"
                :http-request="(file) => handleAvatarSuccess(file, 'idcard_img2')"
              >
                <img v-if="ruleForm.idcard_img2" :src="ruleForm.idcard_img2" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="avatar-uploader" v-if="$route.query.type == 2">
                <el-image
                  v-if="ruleForm.idcard_img2"
                  :src="ruleForm.idcard_img2"
                  :preview-src-list="[ruleForm.idcard_img2]"
                  class="avatar"
                ></el-image>
              </div>
              <div class="photo_p">
                <p class="photo_p_t">身份证国徽面</p>
                <p class="photo_p_t2">图片大小不超过5M</p>
                <p class="photo_p_t2">图片分辨率不低于72dpi</p>
                <el-popover placement="top-start" width="400" trigger="hover">
                  <img style="width: 100%" src="../../assets/images/id-card-1.png" alt="" />
                  <el-button slot="reference" style="padding: 0 !important" type="text">查看示例</el-button>
                </el-popover>
              </div>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item label="毕业证书" prop="graduation_img">
          <el-form-item prop="graduation_img" style="float: left">
            <div class="photo_item">
              <el-upload
              v-if="$route.query.type != 2"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                accept=".jpg, .png, .jpeg"
                :before-upload="beforeAvatarUpload"
                :http-request="(file) => handleAvatarSuccess(file, 'graduation_img')"
              >
                <img v-if="ruleForm.graduation_img" :src="ruleForm.graduation_img" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="avatar-uploader" v-if="$route.query.type == 2">
                <el-image
                  v-if="ruleForm.graduation_img"
                  :src="ruleForm.graduation_img"
                  :preview-src-list="[ruleForm.graduation_img]"
                  class="avatar"
                ></el-image>
              </div>
              <div class="photo_p">
                <p class="photo_p_t">毕业证书</p>
                <p class="photo_p_t2">图片大小不超过5M</p>
                <p class="photo_p_t2">图片分辨率不低于72dpi</p>
                <el-popover placement="top-start" width="400" trigger="hover">
                  <img style="width: 100%" src="../../assets/images/graduation_img.webp" alt="" />
                  <el-button slot="reference" style="padding: 0 !important" type="text">查看示例</el-button>
                </el-popover>
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="degree_img" style="float: left">
            <div class="photo_item">
              <el-upload
              v-if="$route.query.type != 2 || !ruleForm.degree_img"
              :disabled="$route.query.type == 2"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                accept=".jpg, .png, .jpeg"
                :before-upload="beforeAvatarUpload"
                :http-request="(file) => handleAvatarSuccess(file, 'degree_img')"
              >
                <img v-if="ruleForm.degree_img" :src="ruleForm.degree_img" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="avatar-uploader" v-if="$route.query.type == 2 && ruleForm.degree_img">
                <el-image
                  v-if="ruleForm.degree_img"
                  :src="ruleForm.degree_img"
                  :preview-src-list="[ruleForm.degree_img]"
                  class="avatar"
                ></el-image>
              </div>
              <div class="photo_p">
                <p class="photo_p_t">学位证(非必填)</p>
                <p class="photo_p_t2">图片大小不超过5M</p>
                <p class="photo_p_t2">图片分辨率不低于72dpi</p>
                <el-popover placement="top-start" width="400" trigger="hover">
                  <img style="width: 100%" src="../../assets/images/degree_img.webp" alt="" />
                  <el-button slot="reference" style="padding: 0 !important" type="text">查看示例</el-button>
                </el-popover>
              </div>
            </div>
          </el-form-item>
        </el-form-item>
        <div class="title">
          <span>证书信息</span>
          <el-button v-if="$route.query.type != 2" style="margin-left: auto" type="primary" @click="addCert">新增证书信息</el-button>
        </div>
        <el-card style="margin-bottom: 20px;position: relative;" v-for="(item, index) in ruleForm.certs" :key="index">
          <el-form-item
            label="资质类型"
            :prop="'certs.' + index + '.type_id'"
            :rules="{
              required: true,
              message: '请选择资质类型',
              trigger: 'change',
            }"
          >
            <el-select :disabled="$route.query.type == 2" style="width: 100%" v-model="item.type_id" placeholder="请选择">
              <el-option v-for="(item2, index2) in certTypeList" :key="index2" :label="item2.name" :value="item2.id">{{
                item2.name
              }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="职业证书编号"
            :prop="'certs.' + index + '.cert_code'"
            :rules="{
              required: true,
              message: '请输入职业证书编号',
              trigger: 'blur',
            }"
          >
            <el-input :disabled="$route.query.type == 2" v-model="item.cert_code" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item
            label="是否永久有效"
            :prop="'certs.' + index + '.expire_type'"
            :rules="{
              required: true,
              message: '请选择是否永久有效',
              trigger: 'change',
            }"
          >
            <el-select :disabled="$route.query.type == 2" style="width: 100%" v-model="item.expire_type" placeholder="请选择">
              <el-option label="是" :value="1">是</el-option>
              <el-option label="否" :value="2">否</el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="证书有效期"
            :prop="'certs.' + index + '.effective'"
            :rules="{
              required: true,
              message: '请选择证书有效期',
              trigger: 'change',
            }"
            v-if="item.expire_type == 2"
          >
            <el-date-picker
             :disabled="$route.query.type == 2"
              style="width: 100%"
              v-model="item.effective"
              type="daterange"
              range-separator="至"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="证书照片"
            :prop="'certs.' + index + '.cert_imgs'"
            :rules="{
              required: true,
              message: '请上传证书照片',
              trigger: 'change',
            }"
          >
            <div class="photo">
              <div class="photo_item">
                <el-upload
                v-if="$route.query.type != 2"
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  accept=".jpg, .png, .jpeg"
                  :before-upload="beforeAvatarUpload"
                  :http-request="(file) => handleAvatarSuccess(file, 'cert_imgs', index)"
                >
                  <img v-if="item.cert_imgs" :src="item.cert_imgs" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <div class="avatar-uploader" v-if="$route.query.type == 2">
                <el-image
                  v-if="item.cert_imgs"
                  :src="item.cert_imgs"
                  :preview-src-list="[item.cert_imgs]"
                  class="avatar"
                ></el-image>
              </div>
              </div>
            </div>
          </el-form-item>
          <div style="text-align: right;">
            <el-button type="danger" icon="el-icon-search" @click="handelDel(index)">删除证书</el-button>
          </div>
        </el-card>
        <!-- <el-form-item style="margin-top: 20px">
          <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
          <el-button @click="back">取消</el-button>
        </el-form-item> -->
      </el-form>
    </el-card>
    <div class="footer" v-if="$route.query.type != 2">
      <el-button @click="back">关闭</el-button>
      <el-button type="primary" size="medium" @click="submitForm('ruleForm')">保存</el-button>
    </div>
  </div>
</template>

<script>
import { dateFormat } from '../../libs/util';
import { upload, TeacherCertTypes, TeacherSave, TeacherInfo } from '@/api/manage';
export default {
  name: 'addTeacher',
  data() {
    // 自定义手机号校验规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号'));
      } else {
        // 简单的中国大陆手机号正则表达式
        const reg = /^1[3456789]\d{9}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的手机号'));
        }
      }
    };
    // 身份证号校验函数
    const validateIdCard = (rule, value, callback) => {
      const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
      if (!value) {
        callback();
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确的身份证号格式'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        username: undefined,
        idcard: undefined,
        mobile: undefined,
        idcard_img: undefined,
        idcard_img2: undefined,
        graduation_img: undefined,
        degree_img: undefined,
        create_type: this.$route.query.create_type,
        certs: [],
      },
      cert: {
        type_id: undefined,
        cert_code: undefined,
        expire_type: 2,
        start_time: undefined,
        end_time: undefined,
        cert_imgs: undefined,
        effective: undefined,
      },
      certTypeList: [],
      rules: {
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        idcard: [
          // { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validateIdCard, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' },
        ],
        // idcard_img: [{ required: true, message: '请上传身份证人像面照片', trigger: 'change' }],
        // idcard_img2: [{ required: true, message: '请上传身份证国徽面照片', trigger: 'change' }],
        // graduation_img: [{ required: true, message: '请上传毕业证书', trigger: 'change' }],
        type: [{ required: true, message: '请选择资质类型', trigger: 'change' }],
      },
    };
  },
  computed: {},
  watch: {
    'ruleForm.certs': {
      handler(newVal) {
        newVal.forEach((item, index) => {
          if (item.effective && item.effective.length) {
            item.start_time = item.effective[0];
            item.end_time = item.effective[1];
          } else {
            item.start_time = undefined;
            item.end_time = undefined;
          }
        });
      },
      deep: true,
    },
  },
  created() {},
  mounted() {
    this.getTeacherCertTypes();
    if (this.$route.query.id) {
      this.getInfo();
    }
  },
  methods: {
    handelDel(index){
      this.ruleForm.certs.splice(index, 1);
    },
    getInfo() {
      TeacherInfo({ id: this.$route.query.id }).then((res) => {
        this.ruleForm = JSON.parse(JSON.stringify(res.data.info));
        this.$set(this.ruleForm, 'certs', [])
        this.ruleForm.certs = res.data.info.certs.map((item) => {
          if (item.start_time && item.end_time) {
            item.effective = [item.start_time, item.end_time];
          }
          return item;
        });
        // this.ruleForm.certs = res.data.certs;
      });
    },
    addCert() {
      this.ruleForm.certs.push(JSON.parse(JSON.stringify(this.cert)));
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          TeacherSave(this.ruleForm).then((res) => {
            this.$message.success('保存成功');
            this.back();
          });
        } else {
          this.$message.error('请正确填写！');
          return false;
        }
      });
    },
    handleAvatarSuccess(e, type, index) {
      let obj = new FormData();
      obj.append('file', e.file);
      upload(obj).then((res) => {
        if (type != 'cert_imgs') {
          this.ruleForm[type] = res.data.url;
        } else {
           this.$set(this.ruleForm.certs[index], 'cert_imgs', res.data.url);
        }
      });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    back() {
      this.$router.back();
    },
    getTeacherCertTypes() {
      TeacherCertTypes().then((res) => {
        this.certTypeList = res.data.list;
      });
    },
  },
};
</script>

<style scoped>
.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.title {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.title > span {
  font-size: 14px;
  color: #000;
  font-weight: bold;
}
.photo {
  width: 100%;
  display: flex;
  align-items: flex-start;
}
.photo_item {
  display: flex;
  align-items: flex-start;
}
.photo_item:first-child {
  margin-right: 80px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 120px;
  display: flex;
  align-items: center;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 120px;
  display: flex;
  align-items: center;
}
.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 100%;
  display: block;
}
.photo_p {
  margin-left: 10px;
}
.photo_p_t {
  font-size: 12px;
  color: #000;
  margin-bottom: 15px;
  line-height: 20px;
}
.photo_p_t2 {
  font-size: 12px;
  color: #8c939d;
  line-height: 20px;
}
.footer {
  width: 100%;
  height: 60px;
  position: fixed;
  bottom: 0px;
  left: 0;
  z-index: 9;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-left: 210px;
  border-top: 1px solid #e6e6e6;
}
</style>
